<template>
  <view class="container">
    <z-paging ref="paging" v-model="list" @query="getlist">
      <template #top>
        <view class="search-wrapper">
          <u-search
            shape="round"
            v-model="keyword"
            @custom="search"
            @clear="search"
            placeholder="搜索计划"
            :clearabled="true"
            bgColor="#ffffff"
            :searchIcon="require('../../static/s.png')"
          ></u-search>
        </view>
      </template>
      <view class="template-list">
        <view
          v-for="(item, index) in list"
          :key="index"
          :class="{'template-card': true, 'full-width': item.isMerge ==1, 'half-width': item.isMerge !== 1}"
        >
          <view class="card-content" :style="item.isMerge == 1 ? 'background: #000; color: #fff;' : ''">
            <view class="info-section" @click="handleTargetDetail(item)">
              <view class="template-name">
                {{ item.planName || "训练计划模板" }}
              </view>
              <image
                v-if="item.isMerge !== 1"
                :src="
                  isSelected(index)
                    ? '../../static/xz.png'
                    : '../../static/mx.png'
                "
                class="selection-icon"
                @click.stop="toggleSelection(index)"
              ></image>
              <image
                :src="item.isMerge == 1 ? '../../static/del1.png' : '../../static/del.png'"
                class="delete-button"
                @click.stop="confirmDeletePlan(item.id)"
              ></image>
              <view class="button-group" v-if="item.isMerge == 1">
                <button class="detail-button" @click="handleTargetDetail(item)">模板详情</button>
                <view class="divider">|</view>
                <button class="subtemplate-button" @click.stop="openSubTemplateModal(item)">子模板</button>
              </view>
            </view>
          </view>
        </view>
      </view>

      <template #bottom>
        <view class="action-bar">
          <view class="add-button" @click="addData">
            <text class="button-text">新建模板</text>
          </view>
          <view class="share-button" :class="{ 'disabled': selectedIndexes.length === 0 }" @click="selectedIndexes.length > 0 && openShareModal()">
            <text class="button-text">一键分享</text>
          </view>
          <view class="share-button mt20r" @click="selectedIndexes.length > 0 && openMergeModal()">
            <text class="button-text">一键合并</text>
          </view>
        </view>
      </template>
    </z-paging>

    <!-- 分享弹窗 -->
    <view v-if="showShareModal" class="modal">
      <view class="modal-content">
        <view class="modal-header w100 tc f ac">
          <text class="modal-title tc">选择门店</text>
          <view class="close-button" @click="closeShareModal">×</view>
        </view>
        <view class="modal-body">
          <picker mode="selector" :range="storeOptions" range-key="label" @change="onStoreChange">
            <view class="picker">
              {{ selectedStore ? selectedStore.label : '请选择门店' }}
            </view>
          </picker>
        </view>
        <view class="modal-footer">
          <view class="confirm-button" @click="confirmShare" style="width: 100%;">
            <text class="button-text">确定</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 合并弹窗 -->
    <view v-if="showMergeModal" class="modal">
      <view class="modal-content">
        <view class="modal-header w100 tc f ac">
          <text class="modal-title tc">合并计划</text>
          <view class="close-button" @click="closeMergeModal">×</view>
        </view>
        <view class="modal-body">
          <view class="input-group">
            <text class="label">合并后的名称</text>
            <input v-model="mergePlanName" type="text" class="input" placeholder="请输入合并后的名称" />
          </view>
        </view>
        <view class="modal-footer">
          <view class="confirm-button" @click="confirmMerge" style="width: 100%;">
            <text class="button-text">确定</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 子模板弹窗 -->
    <view v-if="showSubTemplateModal" class="modal">
      <view class="subtemplate-modal">
        <view class="modal-header">
          <text class="modal-title">子模板列表</text>
          <view class="close-button" @click="closeSubTemplateModal">×</view>
        </view>
        
        <scroll-view class="subtemplate-grid" scroll-y>
          <view class="grid-container">
            <view 
              v-for="(subItem, subIndex) in currentSubTemplate.ext.his" 
              :key="subIndex" 
              class="subtemplate-card"
              @click="handleTargetDetail(subItem)"
            >
              <view class="card-inner">
                <text class="template-name">{{ subItem.planName }}</text>
              </view>
            </view>
          </view>
        </scroll-view>

        <view class="modal-footer">
          <view class="close-btn" @click="closeSubTemplateModal">
            关闭
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import { plan, savePlanTemplate, deleteMuban, getTenants, sharePlan } from "../../api/fit";
import ZPaging from "../../uni_modules/z-paging/components/z-paging/z-paging.vue";

export default {
  components: { ZPaging, },
  data() {
    return {
      keyword: "",
      list: [],
      selectedIndexes: [],
      showShareModal: false,
      showMergeModal: false,
      showSubTemplateModal: false,
      selectedStore: null,
      mergePlanName: "",
      currentSubTemplate: {},
      storeOptions: [
        { value: 'store1', label: '门店1' },
        { value: 'store2', label: '门店2' },
        { value: 'store3', label: '门店3' },
      ],
    };
  },

  onLoad(options) {
    this.getTenants();
  },

  onShow() {
    this.$refs.paging.reload();
  },

  onUnload() {
    uni.$off("syncRefresh");
  },

  methods: {
    async getTenants() {
      const res = await getTenants();
      this.storeOptions = res.data.map(item => ({
        value: item.id,
        label: item.tenantName
      }));
    },
    addData() {
      uni.navigateTo({
        url: "/pages/muban/index",
      });
    },
    handleTargetDetail(item) {
      console.log(12312312321,'1232321123');
      
      uni.navigateTo({
        url: "/pages/muban/muban?id=" + item.id,
      });
    },
    openSubTemplateModal(item) {
      console.log(item,'222222');
      
      this.currentSubTemplate = item;
      this.showSubTemplateModal = true;
    },
    closeSubTemplateModal() {
      this.showSubTemplateModal = false;
    },
    async getlist(pageNo, pageNum = 20, key) {
      let data = {
        planName: this.keyword,
        page: pageNo,
        size: pageNum,
      };
      const res = await plan(data);
      this.$refs.paging.complete(res.data.list);
    },
    toggleSelection(index) {
      const selectedIndex = this.selectedIndexes.indexOf(index);
      if (selectedIndex === -1) {
        this.selectedIndexes.push(index);
      } else {
        this.selectedIndexes.splice(selectedIndex, 1);
      }
    },
    isSelected(index) {
      return this.selectedIndexes.includes(index);
    },
    openShareModal() {
      this.showShareModal = true;
    },
    closeShareModal() {
      this.showShareModal = false;
    },
    openMergeModal() {
      this.showMergeModal = true;
    },
    closeMergeModal() {
      this.showMergeModal = false;
    },
    onStoreChange(e) {
      this.selectedStore = this.storeOptions[e.detail.value];
    },
    async confirmShare() {
      if (!this.selectedStore) {
        uni.showToast({
          title: '请选择门店',
          icon: 'none'
        });
        return;
      }
      this.showShareModal = false;
      const selectedIds = this.selectedIndexes.map(
        (index) => this.list[index].id
      );
      const shareData = {
        tplIds: selectedIds,
        tenantId: this.selectedStore.value
      };
      const res = await sharePlan(shareData);
      if (res.code === 200) {
        uni.showToast({
          title: '分享成功',
          icon: 'success'
        });
      }
    },
    async confirmMerge() {
      if (!this.mergePlanName) {
        uni.showToast({
          title: '请输入合并后的名称',
          icon: 'none'
        });
        return;
      }
      this.showMergeModal = false;
      const selectedItems = this.selectedIndexes.map(
        (index) => this.list[index]
      );
      console.log(selectedItems,'121212');
      
      const mergedNodes = selectedItems.reduce((acc, item) => {
        return acc.concat(item.nodes);
      }, []);
      console.log(mergedNodes,'222222');
      const ext = selectedItems.map(item => ({
        planName: item.planName,
        nodes: item.nodes,
        id: item.id
      }));
      console.log(ext,'ext');
      
      const result = {
        planName: this.mergePlanName,
        nodes: mergedNodes,
        isMerge: 1,
        ext:{
          his:ext
        } 
      };
      const res = await savePlanTemplate(result);
      if (res.code === 200) {
        uni.showToast({
          title: "合并成功",
          icon: "success",
        });
        // 合并成功后取消选中状态
        this.selectedIndexes = [];
      }
      this.$refs.paging.reload();
    },
    confirmDeletePlan(id) {
      uni.showModal({
        title: '确认删除',
        content: '您确定要删除这个模板吗？',
        success: (res) => {
          if (res.confirm) {
            this.deletePlan(id);
          }
        }
      });
    },
    async deletePlan(id) {
      let arr = [id]
      const res = await deleteMuban(arr);
      if(res.code == 200){
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
        this.getlist(1);
      }
    },
    sharePlan(item) {
      const shareData = {
        title: item.planName || "训练计划模板",
        path: `/pages/muban/muban?id=${item.id}`,
        imageUrl: item.imageUrl || '../../static/default-image.png',
      };

      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession',
        ...shareData,
        success: () => {
          uni.showToast({
            title: '分享成功',
            icon: 'success',
          });
        },
        fail: (err) => {
          console.error('分享失败:', err);
          uni.showToast({
            title: '分享失败，请重试',
            icon: 'none',
          });
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #efefef;
  padding: 20rpx;
}

.template-list {
  padding: 10rpx;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 20rpx;
}

.template-card {
  background: #fff;
  border-radius: 20rpx;
  transform: translateY(0);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
  overflow: hidden;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
  }

  .card-content {
    padding: 24rpx;
  }

  .info-section {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    min-height: 160rpx;
    position: relative;

    .template-name {
      font-size: 32rpx;
      font-weight: 600;
      text-align: center;
      margin-bottom: 10rpx;
    }

    .sub-template-wrapper,
    .sub-template {
      display: none;
    }

    .selection-icon {
      position: absolute;
      top: -10rpx;
      right: 0rpx;
      width: 40rpx;
      height: 40rpx;
      flex-shrink: 0;
    }

    .delete-button {
      position: absolute;
      top: -10rpx;
      left: 0rpx;
      width: 40rpx;
      height: 40rpx;
      cursor: pointer;
      transition: transform 0.3s ease;

      &:hover {
        transform: scale(1.1);
      }
    }

    .button-group {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      margin-top: 20rpx;
      gap: 10rpx;

      .detail-button, .subtemplate-button {
        background: #000;
        color: #fff;
        padding: 10rpx 20rpx;
        border-radius: 10rpx;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

        &:hover {
          background: #333;
        }

        &:active {
          transform: translateY(2rpx);
          box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
        }
      }

      .divider {
        color: rgba(255, 255, 255, 0.8);
        font-size: 32rpx;
        line-height: 32rpx;
        height: 32rpx;
        display: flex;
        align-items: center;
        margin: 0 10rpx;
      }
    }
  }

  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.06);
  }
}

::v-deep .full-width {
  grid-column: span 2;
  background: #000;
  color: #fff !important;
}

.half-width {
  grid-column: span 1;
}

.search-wrapper {
  padding: 20rpx 30rpx;
  background: #ededed;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 100;
}
.action-bar {
  padding: 20rpx 30rpx 50rpx;

  .add-button {
    background: #fff;
    padding: 28rpx;
    border-radius: 16rpx;
    text-align: center;
    transform: translateY(0);
    transition: all 0.3s ease;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.12);
    margin-bottom: 20rpx;

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.08);
    }

    .button-text {
      color: #000;
      font-size: 28rpx;
      font-weight: 500;
      letter-spacing: 2rpx;
    }
  }

  .share-button {
    background: #000;
    padding: 28rpx;
    border-radius: 16rpx;
    text-align: center;
    transform: translateY(0);
    transition: all 0.3s ease;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.12);

    &.disabled {
      background: #ccc;
      pointer-events: none;
    }

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.08);
    }

    .button-text {
      color: #fff;
      font-size: 28rpx;
      font-weight: 500;
      letter-spacing: 2rpx;
    }
  }
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: #fff;
  border-radius: 10rpx;
  width: 80%;
  max-width: 600rpx;
  padding: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #ddd;
  padding-bottom: 10rpx;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
}

.close-button {
  font-size: 32rpx;
  cursor: pointer;
}

.modal-body {
  padding: 20rpx 0;
}

.picker {
  padding: 20rpx;
  background: #f7f7f7;
  border-radius: 10rpx;
  text-align: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  border-top: 1rpx solid #ddd;
  padding-top: 10rpx;
}

.confirm-button {
  background: #000;
  color: #fff;
  padding: 28rpx;
  border-radius: 16rpx;
  text-align: center;
  transform: translateY(0);
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.12);
  cursor: pointer;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.08);
  }

  .button-text {
    color: #fff;
    font-size: 28rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
  }
}

.subtemplate-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 20rpx;
  padding: 10rpx;
}

.subtemplate-item {
  background: #fff;
  border-radius: 20rpx;
  transform: translateY(0);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
  overflow: hidden;
  margin-bottom: 10rpx;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
  }

  .card-content {
    padding: 24rpx;
  }

  .info-section {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    min-height: 160rpx;
    position: relative;

    .template-name {
      font-size: 32rpx;
      font-weight: 600;
      text-align: center;
    }
  }

  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.06);
  }
}

/* 子模板弹窗样式 */
.subtemplate-modal {
  background: #fff;
  border-radius: 20rpx;
  width: 92%;
  max-width: 680rpx;
  max-height: 75vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);

  .modal-header {
    padding: 24rpx;
    border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: space-between;
    align-items: center;

    .modal-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #000;
    }

    .close-button {
      font-size: 36rpx;
      color: #999;
      padding: 8rpx;
      line-height: 1;
    }
  }

  .subtemplate-grid {
    flex: 1;
    padding: 16rpx;
    max-height: 55vh;
    box-sizing: border-box;
  }

  .grid-container {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16rpx;
    padding: 8rpx;
    padding-right: 16rpx; // 确保右侧有足够边距
    box-sizing: border-box;
  }

  .subtemplate-card {
    position: relative;
    border-radius: 12rpx;
    overflow: hidden;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
    }

    .card-inner {
      background: #f8f8f8;
      border-radius: 12rpx;
      padding: 20rpx;
      height: 90rpx; // 减小高度
      display: flex;
      align-items: center; // 垂直居中
      justify-content: center; // 水平居中
      transition: all 0.3s ease;
      
      &:active {
        background: #f0f0f0;
      }
    }

    .template-name {
      font-size: 26rpx;
      font-weight: 600;
      color: #333;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      line-height: 1.4;
      text-align: center; // 文字居中
    }
  }

  .modal-footer {
    padding: 16rpx;
    border-top: 1rpx solid rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: center;

    .close-btn {
      width: 100%;
      height: 72rpx;
      line-height: 72rpx;
      text-align: center;
      background: #000;
      color: #fff;
      border-radius: 36rpx;
      font-size: 28rpx;
      font-weight: 500;
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.98);
        opacity: 0.9;
      }
    }
  }
}
</style>
